package cn.lg.soar.system.auth.service.impl;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.system.auth.entity.DataRule;
import cn.lg.soar.system.auth.entity.DataScope;
import cn.lg.soar.system.auth.entity.Resource;
import cn.lg.soar.system.auth.mapper.DataScopeMapper;
import cn.lg.soar.system.auth.mapper.ResourceMapper;
import cn.lg.soar.system.auth.service.IDataRuleService;
import cn.lg.soar.system.auth.service.IResourceService;
import cn.lg.soar.system.config.AuthCacheKey;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * Resource服务层实现
 * 数据源
 * @author luguoxiang
 * @since 2022-04-30
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ConditionalOnProperty(name = "lg.database.enabled-data-permission", havingValue = "true", matchIfMissing = true)
public class ResourceServiceImpl extends BaseServiceImpl<ResourceMapper, Resource> implements IResourceService {

    @Autowired
    private IDataRuleService dataRuleService;
    @Autowired
    private DataScopeMapper dataScopeMapper;

    @CacheEvict(value = AuthCacheKey.RESOURCE_ID, key = "#entity.code")
    @Override
    public boolean save(Resource entity) {
        return super.save(entity);
    }

    @CacheEvict(value = AuthCacheKey.RESOURCE_ID, key = "#entity.code")
    @Override
    public boolean updateById(Resource entity) {
        return super.updateById(entity);
    }

    @CacheEvict(value = AuthCacheKey.RESOURCE_ID, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<?> list) {
        if (DataUtil.isEmpty(list)) {
            return true;
        }
        AssertUtil.isTrue(super.removeByIds(list), "操作失败");
        List<Long> ruleIds = dataRuleService.listObjs(
                Wrappers.<DataRule>lambdaQuery()
                        .select(DataRule::getId)
                        .in(DataRule::getResourceId, list),
                x -> Long.parseLong(x.toString())
        );
        dataRuleService.removeByIds(ruleIds);
        dataScopeMapper.delete(
                Wrappers.<DataScope>lambdaQuery()
                        .in(DataScope::getResourceId, list)
        );
        return true;
    }

    @Override
    public Resource getByCode(String code) {
        return getOne(
                Wrappers.<Resource>lambdaQuery()
                        .eq(Resource::getCode, code)
        );
    }

}
